#!/bin/sh
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

. /usr/share/misc/shflags || exit 1

DEFINE_string directory /tmp "Bootstat archive directory" d

FLAGS "$@" || exit 1
eval set -- "${FLAGS_ARGV}"

NCPU=$(grep '^processor' /proc/cpuinfo | wc -l)

SUMMARIZE_TIME='
  BEGIN {
    printf "%8s %4s %8s %4s  %s\n", "time", "%cpu", "dt", "%dt", "event"
  }

  {
    # input lines are like this:
    #  $1 = time since boot
    #  $2 = idle time since boot (normalized for NCPU)
    #  $3 = event name
    # input lines are sorted by $1
    uptime = $1 ; idle = $2
    cum_util = (200 * (uptime - idle) / uptime + 1) / 2
    delta = uptime - prev
    if (delta != 0) {
      util = (200 * (delta - idle + prev_idle) / delta + 1) / 2
    } else {
      util = 100
    }
    printf "%8d %3d%% %8d %3d%%  %s\n", uptime, cum_util, delta, util, $3
    prev = uptime ; prev_idle = idle
  }
'

# If there are no arguments on the command line, summarize all the
# events.  If there are arguments, summarize only the named events.
# Error checking is deliberately minimal, to keep this script simple.
if [ $# -eq 0 ]; then
  EVENTS="$(ls ${FLAGS_directory}/uptime-*)"
else
  for EV in "$@"; do
    EVENTS="$EVENTS ${FLAGS_directory}/uptime-$EV"
  done
fi

# Pipeline explained:
#  1st awk program: print times as milliseconds and normalize idle time
#     by NCPU.
#  sort: sort the events by the uptime timestamp.
#  sed: remove '/tmp/uptime-' from the event name.
#  2nd awk program:  produce the summarized output
awk '{print 1000*$1, 1000*$2/'$NCPU', FILENAME}' $EVENTS |
  sort -k 1n | sed 's=[^ ]*uptime-==' | awk "$SUMMARIZE_TIME"
